package com.practice.Http.XML.Coder.Request;

import com.practice.Http.XML.Coder.AbstractHttpXmlDecoder;
import com.practice.Http.XML.Coder.POJO.HttpXmlRequest;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.List;

public class HttpXmlRequsetDecoder extends AbstractHttpXmlDecoder<FullHttpRequest> {

    public HttpXmlRequsetDecoder(Class<?> clazz) {
        this(clazz,
                false);
    }

    public HttpXmlRequsetDecoder(Class<?> clazz, boolean isPrint) {
        super(clazz,
                isPrint);
    }

    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                status,
                Unpooled.copiedBuffer(
                        "Failure : " + status.toString() + "\r\n",
                        CharsetUtil.UTF_8));
        response.headers().set(
                HttpHeaders.Names.CONTENT_TYPE,
                "text/plain; charset=UTF-8");
        ctx.writeAndFlush(
                response).addListener(
                ChannelFutureListener.CLOSE);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception {
        if (!msg.getDecoderResult().isSuccess()) {
            sendError(
                    ctx,
                    HttpResponseStatus.BAD_REQUEST);
        }
        HttpXmlRequest request = new HttpXmlRequest(
                msg,
                (FullHttpRequest) decode0(
                        ctx,
                       msg.content()));
        out.add(request);
    }

}
